package com.gzx.plugin.tjzy.modular.complaint.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzx.plugin.tjzy.modular.complaint.entity.GzxComplaintUser;
import com.gzx.plugin.tjzy.modular.complaint.entity.bo.GzxComplaintUserAddOrEditBo;
import com.gzx.plugin.tjzy.modular.complaint.entity.bo.GzxComplaintUserQueryBo;
import com.gzx.plugin.tjzy.modular.complaint.entity.vo.GzxComplainUserExcelVo;
import com.gzx.plugin.tjzy.modular.complaint.entity.vo.GzxComplaintUserVo;
import com.gzx.plugin.tjzy.modular.complaint.mapper.GzxComplaintUserMapper;
import com.gzx.plugin.tjzy.modular.complaint.service.GzxComplaintUserService;
import com.gzx.plugin.tjzy.modular.gzxcase.entity.GzxCase;
import com.gzx.plugin.tjzy.modular.gzxcase.mapper.GzxCaseMapper;
import com.gzx.plugin.tjzy.modular.liaison.entity.GzxDebtorLiaison;
import com.gzx.plugin.tjzy.modular.liaison.mapper.GzxDebtorLiaisonMapper;
import com.gzx.plugin.tjzy.modular.project.service.GzxProjectService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.common.util.CommonExcelUtil;
import vip.xiaonuo.common.util.MapstructUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 投诉用户信息Service业务层处理
 *
 * @author LionLi
 * @date 2024-10-09
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class GzxComplaintUserServiceImpl implements GzxComplaintUserService {

    private final GzxComplaintUserMapper baseMapper;

    private final GzxDebtorLiaisonMapper debtorLiaisonMapper;

    private final GzxProjectService projectService;

    private final GzxCaseMapper caseMapper;

    /**
     * 查询投诉用户信息
     *
     * @param id 主键
     * @return 投诉用户信息
     */
    @Override
    @DS("tjzy")
    public GzxComplaintUserVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询投诉用户信息列表
     *
     * @param complaintUserQueryBo 查询条件
     * @return 投诉用户信息分页列表
     */
    @Override
    @DS("tjzy")
    public Page<GzxComplaintUserVo> pageList(GzxComplaintUserQueryBo complaintUserQueryBo) {
        LambdaQueryWrapper<GzxComplaintUser> lqw = buildQueryWrapper(complaintUserQueryBo);
        return baseMapper.selectVoPage(new Page<>(complaintUserQueryBo.getCurrent(), complaintUserQueryBo.getSize()), lqw);
    }

    /**
     * 查询符合条件的投诉用户信息列表
     *
     * @param complaintUserQueryBo 查询条件
     * @return 投诉用户信息列表
     */
    @Override
    @DS("tjzy")
    public List<GzxComplaintUserVo> listAll(GzxComplaintUserQueryBo complaintUserQueryBo) {
        LambdaQueryWrapper<GzxComplaintUser> lqw = buildQueryWrapper(complaintUserQueryBo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询符合条件的投诉用户信息列表
     *
     * @param lambdaQueryWrapper 查询条件
     * @return 投诉用户信息列表
     */
    @Override
    @DS("tjzy")
    public List<GzxComplaintUser> selectList(LambdaQueryWrapper<GzxComplaintUser> lambdaQueryWrapper) {
        return baseMapper.selectList();
    }

    private LambdaQueryWrapper<GzxComplaintUser> buildQueryWrapper(GzxComplaintUserQueryBo complaintUserQueryBo) {
        LambdaQueryWrapper<GzxComplaintUser> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(complaintUserQueryBo.getUserName()), GzxComplaintUser::getUserName, complaintUserQueryBo.getUserName());
        if (StringUtils.isNotBlank(complaintUserQueryBo.getMobile())) {
            lqw.eq(GzxComplaintUser::getMobile, CommonCryptogramUtil.doSm1AesEncrypt(complaintUserQueryBo.getMobile()));
        }
        if (StringUtils.isNotBlank(complaintUserQueryBo.getIdCard())) {
            lqw.eq(GzxComplaintUser::getIdCard, CommonCryptogramUtil.doSm1AesEncrypt(complaintUserQueryBo.getIdCard()));
        }
        lqw.orderByDesc(GzxComplaintUser::getId);
        return lqw;
    }

    /**
     * 新增投诉用户信息
     *
     * @param bo 投诉用户信息
     * @return 是否新增成功
     */
    @Override
    @DS("tjzy")
    public void add(GzxComplaintUserAddOrEditBo bo) {
        String complainContent = bo.getComplainContent();
        complainContent = removeSurroundingPTags(complainContent);
        bo.setComplainContent(complainContent);
        GzxComplaintUser add = MapstructUtils.convert(bo, GzxComplaintUser.class);
        String projectNameByCode = projectService.getProjectNameByCode(bo.getPlatformProject());
        add.setPlatformProject(projectNameByCode);
        add.setProjectCode(bo.getProjectCode());
        baseMapper.insert(add);
    }

    /**
     * 修改投诉用户信息
     *
     * @param bo 投诉用户信息
     * @return 是否修改成功
     */
    @Override
    @DS("tjzy")
    public void edit(GzxComplaintUserAddOrEditBo bo) {
//        GzxComplaintUser update = MapstructUtils.convert(bo, GzxComplaintUser.class);
        String complainContent = bo.getComplainContent();
        complainContent = removeSurroundingPTags(complainContent);
        bo.setComplainContent(complainContent);
        GzxComplaintUser add = MapstructUtils.convert(bo, GzxComplaintUser.class);
        add.setMobile(null);
        add.setIdCard(null);
        String projectNameByCode = "";
        try {
            projectNameByCode = projectService.getProjectNameByCode(bo.getPlatformProject());
        } catch (Exception e) {
            baseMapper.updateById(add);
        }
        add.setPlatformProject(projectNameByCode);
        baseMapper.updateById(add);
    }

    /**
     * 校验并批量删除投诉用户信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @DS("tjzy")
    public void deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        baseMapper.deleteBatchIds(ids);
    }

    /**
     * 校验是否是投诉用户
     *
     * @param idCardList
     * @return 投诉用户姓名集合
     */
    @Override
    @DS("tjzy")
    public List<String> checkComplaintUser(List<String> idCardList) {
        List<String> encryptIdCardList = new ArrayList<>();
        idCardList.forEach(idCard -> encryptIdCardList.add(CommonCryptogramUtil.doSm1AesEncrypt(idCard)));
        List<GzxComplaintUser> complaintUserList = baseMapper.selectList(Wrappers.<GzxComplaintUser>lambdaQuery()
                .in(GzxComplaintUser::getIdCard, encryptIdCardList));
        if (CollectionUtil.isEmpty(complaintUserList)) {
            return List.of();
        }
        Map<String, String> complaintUserMap = complaintUserList.stream()
                .collect(Collectors.toMap(GzxComplaintUser::getIdCard, s -> s.getUserName() + ":" + s.getComplainContent(),
                        (existing, replacement) -> existing + "，" + replacement));
        return idCardList.stream()
                .map(complaintUserMap::get)
                .filter(Objects::nonNull).toList();
    }

    /**
     * 校验是否是投诉用户
     *
     * @param phoneList
     * @return 投诉用户姓名集合
     */
    @Override
    @DS("tjzy")
    public Map<String, String> verifyComplaintUser(List<String> phoneList, boolean isAesEncrypt) {
        if (!isAesEncrypt) {
            phoneList = phoneList.stream().map(CommonCryptogramUtil::doSm1AesEncrypt).toList();
        }
        List<GzxComplaintUser> complaintUserList = baseMapper.selectList(Wrappers.<GzxComplaintUser>lambdaQuery()
                .in(GzxComplaintUser::getMobile, phoneList));
        if (CollectionUtil.isNotEmpty(complaintUserList)) {
            return complaintUserList.stream().collect(Collectors.toMap(GzxComplaintUser::getMobile, s -> s.getUserName() + ":" + s.getComplainContent(),
                    (existing, replacement) -> existing + ";" + replacement));
        }
        return Map.of();
    }

    /**
     * 导入投诉用户
     *
     * @param file
     * @throws Exception
     */
    @Override
    @DS("tjzy")
    public void importExcel(MultipartFile file) {
        List<GzxComplainUserExcelVo> gzxComplaintUserVos = CommonExcelUtil.importExcel(file, GzxComplainUserExcelVo.class);
        ArrayList<GzxComplaintUser> list = new ArrayList<>();
        int num = 0;
        for (GzxComplainUserExcelVo gzxComplainUserExcelVo : gzxComplaintUserVos) {
            GzxComplaintUser gzxComplaintUser = new GzxComplaintUser();
            BeanUtil.copyProperties(gzxComplainUserExcelVo, gzxComplaintUser);
            if (gzxComplaintUser.getComplainContent() == null ||
                    gzxComplaintUser.getIdCard() == null ||
                    gzxComplaintUser.getComplainAmount() == null ||
                    gzxComplaintUser.getMobile() == null) {
                throw new CommonException("Excel里的第" + num + "条数据有问题");
            }
            list.add(gzxComplaintUser);
        }
        baseMapper.insertBatch(list);
    }


    /**
     * 客户一键拉黑
     *
     * @param complaintUserAddOrEditBo
     */
    @Override
    @DS("tjzy")
    public void blackoutCustomers(GzxComplaintUserAddOrEditBo complaintUserAddOrEditBo) {
        //根据手机号查询三方联系人
        GzxDebtorLiaison debtorLiaison = debtorLiaisonMapper.selectOne(Wrappers.<GzxDebtorLiaison>lambdaQuery()
                .eq(GzxDebtorLiaison::getLiaisonPhone, CommonCryptogramUtil.doSm1AesEncrypt(complaintUserAddOrEditBo.getMobile()))
                .eq(GzxDebtorLiaison::getProjectCode, complaintUserAddOrEditBo.getPlatformProject())
                .orderByDesc(GzxDebtorLiaison::getId)
                .last("limit 1"));
        if (debtorLiaison == null) {
            throw new CommonException("客户拉黑失败，匹配不到身份证号");
        }
        GzxComplaintUser complaintUser = new GzxComplaintUser();
        complaintUser.setMobile(complaintUserAddOrEditBo.getMobile());
        complaintUser.setIdCard(debtorLiaison.getDebtorCardId());
        complaintUser.setComplainImportant(complaintUserAddOrEditBo.getComplainImportant());
        complaintUser.setProjectCode(complaintUserAddOrEditBo.getProjectCode());
        complaintUser.setComplainContent(complaintUserAddOrEditBo.getComplainContent());
        GzxCase gzxCase = caseMapper.selectOne(Wrappers.<GzxCase>lambdaQuery()
                .eq(GzxCase::getProjectCode, complaintUserAddOrEditBo.getProjectCode())
                .eq(GzxCase::getDebtorCardId, CommonCryptogramUtil.doSm1AesEncrypt(debtorLiaison.getDebtorCardId())));
        if (gzxCase == null) {
            throw new CommonException("匹配不到案件");
        }
        complaintUser.setComplainAmount(gzxCase.getCleanLoanAmount());
        baseMapper.insert(complaintUser);
    }

    public static String removeSurroundingPTags(String htmlContent) {
        if (htmlContent.startsWith("<p>") && htmlContent.endsWith("</p>")) {
            return htmlContent.substring(3, htmlContent.length() - 4);
        }
        return htmlContent; // 如果不符合条件，则返回原字符串
    }
}
